package 多线程.InterruptDemo;

/**
 * @author : K k
 * @date : 16:17 2020/10/13
 */
public class InterruptDemo {
    static volatile Object lock = new Object();
    static volatile boolean stop = false;

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        if (Thread.currentThread().isInterrupted()) {
                            System.out.println("Someone interrupted me0.");
                        } else {
                            Thread.currentThread().interrupt();
                            Thread.sleep(2000);
                            System.out.println("Thread0 is running...");
                        }
                    } catch (InterruptedException e) {
                        //由于抛出异常会让中断状态复位 需要手动再设置中断或设置状态位flag
                        //Thread.currentThread().interrupt();
                        stop=true;
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();

        /*Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!stop){
                    if(Thread.currentThread().isInterrupted()) {
                        System.out.println("Someone interrupted me1.");
                    }else{
                        System.out.println("Thread1 is running...");
                    }
                }
            }
        });
        thread.start();*/

        try {
            Thread.sleep(3000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
